package com.xique.system.controller;

import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.domain.R;
import com.xique.common.core.enums.UserType;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.controller.BaseController;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.core.web.domain.PageResult;
import com.xique.common.core.web.page.TableDataInfo;
import com.xique.common.log.annotation.Log;
import com.xique.common.log.enums.BusinessType;
import com.xique.common.security.annotation.PreAuthorize;
import com.xique.system.api.dto.AdminListDTO;
import com.xique.system.api.dto.OperateDTO;
import com.xique.system.api.dto.SystemUserDTO;
import com.xique.system.api.model.LoginSystemUser;
import com.xique.system.bean.domain.SystemRole;
import com.xique.system.bean.domain.SystemUser;
import com.xique.system.bean.request.SystemUserChangePwdRequest;
import com.xique.system.constants.SystemConstants;
import com.xique.system.service.biz.service.ISystemUserBizService;
import com.xique.system.service.service.ISystemRoleService;
import com.xique.system.service.service.ISystemUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shd
 * @create 2021/11/11 14:58
 */
@RestController
@RequestMapping("/user")
public class SystemUserController extends BaseController {

    @Autowired
    private ISystemUserBizService sysUserBizService;

    @Autowired
    private ISystemUserService userService;

    @Autowired
    private ISystemRoleService roleService;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{username}")
    @ApiOperation("登录时获取当前用户信息")
    public R<LoginSystemUser> info(@PathVariable("username") String username) {
        return sysUserBizService.getSystemUserByUserName(username);
    }

    @GetMapping("/info/{username}/{password}")
    @ApiOperation("登录时获取当前用户信息")
    public R<LoginSystemUser> infoV1(@PathVariable("username") String username, @PathVariable("password") String password) {
        return sysUserBizService.getSystemUserByUserNameV1(username, password);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("获取用户信息")
    public AjaxResult getInfo() {
        return sysUserBizService.getInfo();
    }


    /**
     * 获取当前用户私钥信息
     */
    @GetMapping("/key/{username}")
    @ApiOperation("登录时获取当前用户私钥信息")
    public R<String> key(@PathVariable("username") String username) {
        return sysUserBizService.getSystemUserKeyByUserName(username);
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SystemUser user) {
        user.setParkId(SecurityUtils.getParkId());
        if (UserConstants.Platform.ADMIN_SERVICE.equals(SecurityUtils.getPlatformType())) {
            user.setUserType(UserConstants.UserType.SERVICE_MANAGER);
        }
        if (UserConstants.Platform.ADMIN_PROJECT.equals(SecurityUtils.getPlatformType())) {
            user.setUserType(UserConstants.UserType.PROJECT_MANAGER);
            user.setType(UserConstants.Type.MANAGER);
        }
        startPage();
        List<SystemUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        return sysUserBizService.getInfo(userId);
    }

    /**
     * 新增用户
     */
    @PreAuthorize(hasPermi = "system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SystemUser user) {
        if (StringUtils.isNotEmpty(user.getLoginName())
                && UserConstants.NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return AjaxResult.error("创建新用户失败，登录账号已存在，请重新输入");
        }
//        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
//            return AjaxResult.error("创建新用户失败，用户名称已存在，请重新输入");
//        } else if (StringUtils.isNotEmpty(user.getLoginName())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
//            return AjaxResult.error("创建新用户失败，登录账号已存在，请重新输入");
//        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return AjaxResult.error("创建新用户失败，手机号码已存在，请重新输入");
//        } else if (StringUtils.isNotEmpty(user.getEmail())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        if (UserConstants.Platform.ADMIN.equals(SecurityUtils.getPlatformType())) {
            user.setUserType(UserConstants.UserType.MANAGER);
        }
        if (UserConstants.Platform.ADMIN_SERVICE.equals(SecurityUtils.getPlatformType())) {
            user.setUserType(UserConstants.UserType.SERVICE_MANAGER);
        }
        if (UserConstants.Platform.ADMIN_PROJECT.equals(SecurityUtils.getPlatformType())) {
            user.setParkId(SecurityUtils.getParkId());
            user.setUserType(UserConstants.UserType.PROJECT_MANAGER);
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping(value = "/saveClientUser")
    public R<Long> saveClientUser(@RequestBody SystemUserDTO userDTO) {
        SystemUser user = OrikaUtil.convert(userDTO, SystemUser.class);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
//        else if (StringUtils.isNotEmpty(user.getPhonenumber())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
//        } else if (StringUtils.isNotEmpty(user.getEmail())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        SystemRole search = new SystemRole();
        search.setRoleKey(SystemConstants.ROLE_KEY_CLIENT_MNG);
        List<SystemRole> roleList = roleService.selectRoleList(search);
        if (CollectionUtils.isNotEmpty(roleList)) {
            List<Long> roleIds = roleList.stream().map(SystemRole::getRoleId).collect(Collectors.toList());
            user.setRoleIds(roleIds.toArray(new Long[roleIds.size()]));
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setType(UserConstants.Type.CLIENT);
        int count = userService.insertUser(user);
        if (count <= 0) {
            return R.fail("添加用户失败");
        }
        return R.ok(user.getUserId());
    }

    /**
     * 修改用户
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SystemUser user) {
        userService.checkUserAllowed(user);
//        if (StringUtils.isNotEmpty(user.getPhonenumber())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
//        } else if (StringUtils.isNotEmpty(user.getEmail())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize(hasPermi = "system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeClientUser")
    public R<Boolean> removeClientUser(Long userId) {
        int count = userService.deleteUserByIds(new Long[]{userId});
        if (count <= 0) {
            return R.fail("删除失败");
        }
        return R.ok();
    }

    /**
     * 重置密码
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SystemUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }


    /**
     * 修改密码
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changePwd")
    public AjaxResult changePwd(@RequestBody SystemUserChangePwdRequest request) {
        SystemUser user = userService.selectSystemUserById(request.getUserId());
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("未找到对应用户");
        }
        if (!SecurityUtils.matchesPassword(request.getOldPassword(), user.getPassword())) {
            return AjaxResult.error("原密码错误，请重新输入");
        }
        if (SecurityUtils.matchesPassword(request.getNewPassword(), user.getPassword())) {
            return AjaxResult.error("新密码不可与原密码相同，请重新输入");
        }
        user.setPassword(SecurityUtils.encryptPassword(request.getNewPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SystemUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize(hasPermi = "system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SystemUser user = userService.selectSystemUserById(userId);
        List<SystemRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SystemUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @GetMapping("/adminList")
    public R<List<AdminListDTO>> adminList() {
        List<SystemUser> list = userService.selectUserList(new SystemUser());

        List<AdminListDTO> vos = OrikaUtil.converts(list, AdminListDTO.class);

        return R.ok(vos);
    }

    @GetMapping("/getOperate")
    public R<OperateDTO> operate(Long operateId) {
        SystemUser user = userService.getById(operateId);

        OperateDTO dto = new OperateDTO();
        dto.setOperateId(user.getUserId());
        dto.setOperateName(user.getUserName());

        return R.ok(dto);
    }

    @GetMapping("/getOperateList")
    public R<List<OperateDTO>> operateList(String operateIds) {
        List<SystemUser> list = userService.listByIds(Arrays.asList(operateIds.split(",")));

        List<OperateDTO> dtos = new ArrayList<>(list.size());
        list.forEach(item -> {
            OperateDTO dto = new OperateDTO();
            dto.setOperateId(item.getUserId());
            dto.setOperateName(item.getUserName());

            dtos.add(dto);
        });

        return R.ok(dtos);
    }

    /**
     * 根据parkID获取岗亭用户列表
     */
    @Log(title = "根据parkID获取岗亭用户列表")
    @GetMapping(value = "/clientMngList/{parkId}")
    public AjaxResult clientMngList(@PathVariable(required = false) Long parkId) {
        if (parkId == null) {
            parkId = SecurityUtils.getParkId();
            if (parkId == null) {
                return AjaxResult.error("车场ID不可为空");
            }
        }
        List<SystemUser> parkUserVoList = userService.selectListByParkIdAndType(parkId, UserType.CLIENT_MNG.getType());
        return AjaxResult.success(parkUserVoList);
    }

    /**
     * 根据parkID分页获取岗亭用户列表
     *
     * @return /
     */
    @PostMapping(value = "/selectPageList")
    public R<PageResult> selectPageList(@RequestBody SystemUserDTO userDTO) {
        PageResult result = userService.selectPageList(userDTO.getPageNum(), userDTO.getPageSize(), userDTO.getUserId(),
                userDTO.getParkId(), UserType.CLIENT_MNG.getType());
        return R.ok(result);
    }

    /**
     * 获取项目用户列表（不分页）
     */
    @PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/project/list")
    public TableDataInfo parkUserList(SystemUser user) {
        user.setParkId(SecurityUtils.getParkId());
        if (UserConstants.Platform.ADMIN_PROJECT.equals(SecurityUtils.getPlatformType())) {
            user.setUserType(UserConstants.UserType.PROJECT_MANAGER);
        }
//        startPage();
        List<SystemUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @GetMapping(value = "/selectRoleSystemUserList")
    public R<List<SystemUserDTO>> selectRoleSystemUserList(Long userId) {
        return sysUserBizService.selectRoleSystemUserList(userId);
    }
}
